package com.wowangz.cms.user.api;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.google.gson.Gson;
import com.wowangz.cms.common.pojo.AjaxDataEntity;
import com.wowangz.cms.common.utils.CommonCrypto;
import com.wowangz.cms.common.utils.SysConstant;
import com.wowangz.cms.dailyoperation.storeuser.service.AdminUserService;
import com.wowangz.cms.syscore.InitEnvironment;
import com.wowangz.cms.syscore.IssTransactionContainer;
import com.wowangz.cms.syscore.api.BaseController;
import com.wowangz.cms.syscore.api.JSONFactory;
import com.wowangz.cms.syscore.api.UserContext;
import com.wowangz.cms.syscore.utils.EncryptUtil;
import com.wowangz.cms.syscore.utils.LoadBaseDataConstants;
import com.wowangz.cms.syscore.utils.MessageResourcesUtils;
import com.wowangz.cms.syscore.utils.SystemConfig;
import com.wowangz.cms.systemmanage.passwordpolicy.pojo.PasswordPolicyHistory;
import com.wowangz.cms.systemmanage.passwordpolicy.service.PasswordPolicyHistoryService;
import com.wowangz.cms.user.pojo.User;
import com.wowangz.cms.user.service.UserService;

/**
 *
 * @描述：用户忘记密码。发送邮件修改密码
 * @author HUANGYUAN
 * @TIME:2015年8月28日 下午12:17:54
 */
@Scope("prototype")
@Controller
@SuppressWarnings("unchecked")
public class ResetPassController extends BaseController {
	// 获得配置文件中配置的商户端的访问地址
	private static SystemConfig systemConfig=new SystemConfig("storeurl");
	private static Map<String ,Object> systemConfigMap = systemConfig.getKeyValueMap();
	
	/**
	 * 创建发送邮件
	 * 时间  : 2015年12月14日 下午4:07:42
	 * @param email
	 * @param userid
	 * @param request
	 * @param isBatch
	 * @return
	 * @throws Exception
	 */
	public Map<String, Object> createEmail(String email, String userid, HttpServletRequest request, String isBatch)
			throws Exception {
		// 获得商户端的访问地址
		String storeurl = systemConfigMap.get("storeurl").toString();
		// 获得项目的访问地址
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/systemmanage/resetManageUser/toResetPasswordPage.web?";
		// 获得秘钥
		String secretKey = UUID.randomUUID().toString().replaceAll("-", ""); // 密钥
		String key = email + "-" + userid + "-" + secretKey + "-" + isBatch;
		EncryptUtil encryptUtil = new EncryptUtil();
		// 加密KEY
		String encode = encryptUtil.encrypt(key);
		long startTime = new Date().getTime();
		User user = getUserService(false).findUserById(userid);
		String name = "";
		if (StringUtils.equals(isBatch, "yes")) {
			AdminUserService adminUserService = (AdminUserService) IssTransactionContainer.getInstance(AdminUserService.class, false);
			name = adminUserService.findAdminUserById(userid).getLoginname();
			List<Object> list = InitEnvironment.getBaseDataCacheMap().get(LoadBaseDataConstants.PASSWORDPOLICY);
			String info = new Gson().toJson(list);
			info = encryptUtil.encrypt(info);
			basePath = storeurl + "/systemmanage/reset/resetStorePasswordToPage.web?info=" + info + "&storeurl="+ storeurl + "&";
		} else {
			if (user != null) {
				name = user.getLoginname();
			}
		}
		String resetPassHref = basePath + "params=" + encode + "&startTime=" + startTime;
		String emailContent = "请勿回复本邮件.<br/><br/>&nbsp;&nbsp;&nbsp;&nbsp;<a href=" + resetPassHref + " target='_BLANK'>点击我重新设置密码</a><br/>"
				+ "<br/>&nbsp;&nbsp;&nbsp;&nbsp;tips:本邮件超过30分钟,链接将会失效，需要重新联系管理员重置密码<br/>\t";
		StringBuffer mailText = new StringBuffer();
		mailText.append(name + "&nbsp;您好:<br/>&nbsp;&nbsp;&nbsp;&nbsp;我们收到来自资金云平台帐号的密码重设要求,请点击下列链接以重设您的密码：");
		mailText.append(emailContent);
		mailText.append("<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;如果您不想要做以上修改，或者您没有提出此要求，请忽视此电子邮件。");
		Map<String, Object> messageMap = new HashMap<String, Object>();
		messageMap.put("content", mailText.toString());
		messageMap.put("email", email);
		messageMap.put("subject", "资金云平台 – 密码找回/修改");
		return messageMap;
	}

	/**
	 * 获得Service服务信息
	 *
	 * @param flag
	 *            是否开启事务
	 * @return
	 */
	private UserService getUserService(boolean flag) {
		return (UserService) IssTransactionContainer.getInstance(UserService.class, flag);
	}

	/**
	 * 获得前几次的修改密码是否相同
	 *
	 * @author HUANGYUAN
	 * @时间 2015年8月17日 上午10:04:57
	 * @param response
	 * @param request
	 * @描述
	 */
	@RequestMapping(value = "/systemmanage/resetManageUser/isValidByTop.json", method = {RequestMethod.GET,RequestMethod.POST})
	public void isValidByTop(HttpServletResponse response, HttpServletRequest request) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		String userid = request.getParameter("userid");
		String loginname = "";
		String status = "n";
		String info = "";
		try {
			UserService userService = (UserService) IssTransactionContainer.getInstance(UserService.class, false);
			User user = userService.findUserById(userid);
			if (user != null) {
				loginname = user.getLoginname();
			} else {
				loginname = getUserContext().getLoginUser().getLoginname();
			}
			paramMap.put("messagecode", SysConstant.YesOrNo.NO);
			PasswordPolicyHistoryService service = (PasswordPolicyHistoryService) IssTransactionContainer.getInstance(
					PasswordPolicyHistoryService.class, false);
			List<Object> list = InitEnvironment.getBaseDataCacheMap().get(LoadBaseDataConstants.PASSWORDPOLICY);
			Map<String, Object> passwordMap = list.size() > 0 ? (Map<String, Object>) list.get(0) : null;
			Object object = passwordMap.get("pwdHistory");
			paramMap.put("top", Integer.parseInt(object.toString()));
			paramMap.put("loginname", loginname);
			List<PasswordPolicyHistory> historyList = service.queryPasswordPolicyHistoryList(paramMap);
			String newPassword = request.getParameter("param");
			if (StringUtils.isNotEmpty(newPassword)) {
				if (historyList.size() > 0) {
					for (PasswordPolicyHistory history : historyList) {
						if (StringUtils.equals(CommonCrypto.encryptSHAEncoder(newPassword), history.getPassword())) {
							status = "n";
							info = MessageResourcesUtils.getMessage(request, "common.password.isCheck") + object.toString()
									+ MessageResourcesUtils.getMessage(request, "common.password.isCheck1");
							break;
						} else {
							status = "y";
							info = MessageResourcesUtils.getMessage(request, "common.tip.password.alert1");
						}
					}
				} else {
					status = "y";
					info = MessageResourcesUtils.getMessage(request, "common.tip.password.alert1");
				}
			} else {
				info = MessageResourcesUtils.getMessage(request, "common.password.input.new.password");
				status = "n";
			}
		} catch (Exception e) {
			e.printStackTrace();
			info = MessageResourcesUtils.getMessage(request, "common.password.input.new.password");
			status = "n";
		} finally {
			Map<String, Object> resultMap = new HashMap<String,Object>();
			resultMap.put("info", info);
			resultMap.put("status", status);
			try {
				response.getWriter().write(new Gson().toJson(resultMap));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}


	/**
	 * 进入运营端管理员修改密码的页面
	 * @param model
	 * @param response
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/resetManageUser/toResetPasswordPage.web", method = {RequestMethod.GET,RequestMethod.POST})
	public String toResetPasswordPage(Model model, HttpServletResponse response, HttpServletRequest request) {
		try {
			String param = request.getParameter("params");
			EncryptUtil encryptUtil = new EncryptUtil();
			param = new String(encryptUtil.decrypt(param));
			String[] params = param.split("-");
			String userid = params[1];
			String isBatch = "";
			if (params.length > 3) {
				isBatch = params[3];
			}
			String startTime = request.getParameter("startTime");
			if (StringUtils.isNotEmpty(startTime)) {
				long millis = new Date().getTime();
				long start = Long.parseLong(startTime);
				long current = millis - start;
				long time = current / (60 * 1000);
				if (time > 100) {
					model.addAttribute("flag", "INVALIDE");
				}
			}
			model.addAttribute("id", userid);
			model.addAttribute("isBatch", isBatch);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/WEB-INF/jsp/systemmanage/user/reset";
	}

	/**
	 * @author HUANGYUAN
	 * @时间 2015年7月30日 上午11:01:42
	 * @param request
	 * @param response
	 * @描述 重置密码
	 */
	@RequestMapping(value = "/systemmanage/manageUser/resetUserPassword.json", method = { RequestMethod.POST})
	public void resetUserPassword(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		String isBatch = request.getParameter("isBatch");
		System.out.println(isBatch);
		String status = "n";
		String info = "";
		try {
			User user = getUserService(false).findUserById(id);
			if (user != null) {
				// 保存密码历史
				PasswordPolicyHistory history = new PasswordPolicyHistory();
				history.setLoginname(user.getLoginname());
				history.setPassword(user.getPassword());
				history.setInputtime(new Date());
				PasswordPolicyHistoryService service = (PasswordPolicyHistoryService) IssTransactionContainer.getInstance(
						PasswordPolicyHistoryService.class, true);
				service.insertPasswordHistory(history);
				String password = request.getParameter("password");
				// 获得新的密码
				password = CommonCrypto.encryptSHAEncoder(password);
				user.setPassword(password);
				user.setModifyuserid(user.getId());
				user.setPwdchangedate(new Date());
				user.setModifytime(new Date());
				getUserService(true).modify(user);
				String inforMessage = MessageResourcesUtils.getMessage(request, "systemmanage.user.spassword.update.success");
				// 设置修改密码成功的信息
				info = inforMessage;
				status = "y";
			} else {
				info = MessageResourcesUtils.getMessage(request, "systemmanage.user.spassword.update.error"); 
			}
		} catch (Exception e) {
			// 修改密码错误时的错误信息
			info = MessageResourcesUtils.getMessage(request, "systemmanage.user.spassword.update.error"); 
			e.printStackTrace();
		} finally {
			try {
				// 这句话的意思，是让浏览器用utf8来解析返回的数据
				response.setHeader("Content-type", "text/html;charset=UTF-8");
				Map<String, Object> map = new HashMap<String,Object>();
				map.put("status", status);
				map.put("info", info);
				String result = new Gson().toJson(map);
				response.getWriter().write(result);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 密码修改/找回时，发送邮件
	 *
	 * @param userId
	 * @param request
	 */
	@RequestMapping(value = "/systemmanage/user/sendMail.web", method = RequestMethod.POST)
	public void sendMail(HttpServletRequest request, HttpServletResponse response, Model model) {
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		UserService userService = getUserService(false);
		UserContext userContext = getUserContext();
		if (userContext == null) {
			userContext = new UserContext();
		}
		// 获得批量修改密码的ID集合
		String ids = request.getParameter("ids");
		try {
			String email = request.getParameter("email");
			String userid = request.getParameter("id");
			if (StringUtils.isNotEmpty(ids)) {
				String[] userids = ids.split(",");
				for (int i = 0; i < userids.length; i++) {
					String param = userids[i];
					String[] params = param.split(":");
					Map<String, Object> messageMap = createEmail(params[1], params[0], request, "yes");
					userService.sendEmailData(messageMap);;
				}
			} else {
				Map<String, Object> messageMap = createEmail(email, userid, request, "no");
				userService.sendEmailData(messageMap);;
			}
			userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "systemtmanage.user.email.send.success"));
		} catch (Exception e) {
			// 用户可能会输错邮箱导致报错 那么得返回错误信息页面告知用户，并自动跳转到重置密码页面
			e.printStackTrace();
			userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "systemtmanage.user.email.send.error"));
		} finally {
			try {
				response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, userContext));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
